package priv.dajie.tzzq;

import org.apache.http.Header;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import priv.dajie.tzzq.bot.exception.NetworkException;

import java.util.ArrayList;
import java.util.List;

public class BaseStatic {
    private static CloseableHttpClient httpClient;

    static {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader(HttpHeaders.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"));
        headers.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, "zh-CN,zh;q=0.9"));
        httpClientBuilder.setDefaultHeaders(headers);
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true));
        httpClient = httpClientBuilder.build();
    }

    public static String open(HttpRequestBase httpRequest) {
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            return EntityUtils.toString(httpResponse.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            throw new NetworkException("无法打开网页: " + e);
        }finally {

        }
    }


}
